
package com.zhu.salesmanagement.views;

import java.util.ArrayList;
import java.util.List;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.InputMessageActivity;
import com.zhu.salesmanagement.StoreEvaluationActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.models.CEvaluationItem;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.app.AlertDialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 大区考核界面
 */
public class ComprehensiveEvaluationView extends LinearLayout implements View.OnClickListener {

    private final static String TAG = "zhu";

    private final static int CHECKLIST_STATUS_QUERY_TOKEN = 990;
    private final static int S_STATUS_QUERY_TOKEN = 998;
    public final static String SPLIT_ROW = ";";
    public final static String SPLIT_RANK = "&";

    private LinearLayout mBodyLayout = null;
    private ScrollView mScrollView = null;
    private boolean isInited = false;
    private DataQueryHandler mDataQueryHandler = null;
    private EditText mXunxiText = null;
    private List<CEvaluationItem> mList = new ArrayList<CEvaluationItem>();
    private StoreEvaluationActivity mStoreEvaluationActivity = null;
    private TextView mNumberView = null;
    private String[] mBijinpingArray = null;
    private String[] mBijinpingValueArray = null;

    public ComprehensiveEvaluationView(Context context) {
        super(context);
        mDataQueryHandler = new DataQueryHandler(context.getContentResolver());
    }

    public ComprehensiveEvaluationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mDataQueryHandler = new DataQueryHandler(context.getContentResolver());
    }

    @Override
    public void onFinishInflate() {
        setupViews();
        super.onFinishInflate();
    }

    /**
     * 设置界面
     */
    private void setupViews() {
        mScrollView = (ScrollView) this.findViewById(R.id.ce_scrollview);
        mBodyLayout = (LinearLayout) this.findViewById(R.id.ce_bodyView);
        mXunxiText = (EditText) this.findViewById(R.id.ce_xunxiText);
        mNumberView = (TextView) this.findViewById(R.id.ceview_number);
    }

    /**
     * 初始化数据
     * @activity activity
     */
    public void initData(StoreEvaluationActivity activity) {
        if (isInited) {
            return;
        }
        mStoreEvaluationActivity = activity;
        isInited = true;
        mBijinpingArray = this.getContext().getResources().getStringArray(R.array.compare_type);
        mBijinpingValueArray = this.getContext().getResources().getStringArray(R.array.compare_value);

        startCheckListQuery(mStoreEvaluationActivity.getVisitTaskInfo().sAreaID);
    }

    /**
     * 查询大区考核项目
     * @param aearid 大区ID
     */
    private void startCheckListQuery(String aearid){
        String where = SalesSettings.IntegrationStandardColumns.AREAID + " = \'" + aearid + "\'";
        mDataQueryHandler.startQuery(CHECKLIST_STATUS_QUERY_TOKEN, null, SalesSettings.IntegrationStandardColumns.CONTENT_URI, 
                new String[]{ SalesSettings.IntegrationStandardColumns.ITEMNO, SalesSettings.IntegrationStandardColumns.ITEMDES}, where, null, null);
    }

    private void startQuery(String storeid){
        String where = SalesSettings.VisitedStoresColumns.STOREID + " = \'" + storeid + "\'";
        mDataQueryHandler.startQuery(S_STATUS_QUERY_TOKEN, null, SalesSettings.VisitedStoresColumns.CONTENT_URI, 
                new String[]{ SalesSettings.VisitedStoresColumns.CHECKRESULT, SalesSettings.VisitedStoresColumns.CHECKRINFO}, where, null, null);
    }

    /**
     * 更新界面
     */
    private void updateBody(){
        for(int i = 0; i < mList.size(); i++){
            mBodyLayout.addView(getItemView(mList.get(i)));
        }
    }

    /**
     * 更新列表项界面
     * @param item 考核项信息
     */
    private View getItemView(CEvaluationItem item) {
        View view = LayoutInflater.from(this.getContext()).inflate(R.layout.cevaluation_listitem,
                null);
        Button selectv = (Button)view.findViewById(R.id.celistitem_select);
        selectv.setOnClickListener(this);
        selectv.setTag(item);
        selectv.setText(getSelectCompareString(item.value));
        TextView textView = (TextView) view.findViewById(R.id.celistitem_name);
        textView.setText(item.sName);
        return view;
    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v != null){
            switch(v.getId()){
                case R.id.celistitem_select:
                    popSelectCompareDialog((Button)v);
                    break;
            }
        }
    }

    /**
     * 禁用父界面滑动
     */
    public void requestDisallowEvent(boolean disable) {
        getParent().requestDisallowInterceptTouchEvent(disable);
        this.requestDisallowInterceptTouchEvent(disable);
        mScrollView.requestDisallowInterceptTouchEvent(disable);
    }

    /**
     * 保存数据
     */
    public void saveData(long dbid){
        String kaopin = getKaoPin();
        String xunxi = mXunxiText.getText().toString();
        if(kaopin.length() == 0 && xunxi.trim().length() == 0){
            return;
        }

        ContentValues values = new ContentValues();
        if(kaopin.length() > 0){
            values.put(SalesSettings.VisitedStoresColumns.CHECKRESULT, kaopin);
        }
        if(xunxi.trim().length() > 0){
            values.put(SalesSettings.VisitedStoresColumns.CHECKRINFO, xunxi);
        }
        getContext().getContentResolver().update(SalesSettings.VisitedStoresColumns.getContentUri(dbid, false), values, null, null);
        Actions.toastShort(getContext(), getContext().getString(R.string.save_success));
    }

    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case S_STATUS_QUERY_TOKEN:
                    updateDataFromCursor(cursor);
                    break;
                case CHECKLIST_STATUS_QUERY_TOKEN:
                    updateCheckListFromCursor(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case S_STATUS_QUERY_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 获取所有考评结果
     */
    private String getKaoPin(){
        String text = "";
        for(int i = 0; i < mBodyLayout.getChildCount(); i++){
            View view = mBodyLayout.getChildAt(i);
            Button b = (Button) view.findViewById(R.id.celistitem_select);
            CEvaluationItem item = (CEvaluationItem)b.getTag();
            text += item.sID + SPLIT_RANK + item.value + SPLIT_ROW;
            item.savedvalue = item.value;
        }
        return text;
    }

    /**
     * 更新考核内容
     */
    private void updateCheckListFromCursor(Cursor cursor){
        mList.clear();
        int idindex = cursor.getColumnIndexOrThrow(SalesSettings.IntegrationStandardColumns.ITEMNO);
        int desindex = cursor.getColumnIndexOrThrow(SalesSettings.IntegrationStandardColumns.ITEMDES);
        try{
            while (cursor.moveToNext()) {
                CEvaluationItem item = new CEvaluationItem();
                item.sID = cursor.getString(idindex);
                item.sName = cursor.getString(desindex);
                mList.add(item);
            }
        }catch(Exception e){
            
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        updateData();
        //startQuery(mStoreEvaluationActivity.getVisitTaskInfo().id);
    }

    /**
     * 更新考核结果数据
     */
    private void updateDataFromCursor(Cursor cursor){
        int resultindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRESULT);
        int infoindex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRINFO);
        String result = null;
        String info = null;
        try{
            while (cursor.moveToNext()) {
                result = cursor.getString(resultindex);
                info = cursor.getString(infoindex);
            }
        }catch(Exception e){
            
        }finally{
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        mXunxiText.setText(info);
        parseKaopin(result);
        updateBody();
    }

    /**
     * 刷新界面数据
     */
    private void updateData(){
        mXunxiText.setText(mStoreEvaluationActivity.getVisitTaskInfo().sCheckInfo);
        parseKaopin(mStoreEvaluationActivity.getVisitTaskInfo().sCheckResult);
        updateBody();
        mNumberView.setText(this.getContext().getString(R.string.gongsanxiang, mList.size()));
    }

    private CEvaluationItem getCEvaluationItem(String id){
        for(int i = 0; i < mList.size(); i++){
            CEvaluationItem item = mList.get(i);
            if(item.sID.equals(id)){
                return item;
            }
        }
        return null;
    }

    /**
     * 解析考评结果
     */
    private void parseKaopin(String text){
        if(text != null && text.trim().length() > 1){
            String[] rowGoods = text.split(SPLIT_ROW);
            for (int i = 0; i < rowGoods.length; i++) {
                if (Actions.DEBUG) {
                    Log.e("zhu", "xx=" + rowGoods[i]);
                }
                String[] rankGoods = rowGoods[i].split(SPLIT_RANK);
                CEvaluationItem item = getCEvaluationItem(rankGoods[0]);
                if(item != null){
                    item.value = rankGoods[1];
                    item.savedvalue = item.value;
                }
            }
        }
    }

    /**
     * 弹出选择考评项
     */
    private void popSelectCompareDialog(final Button button){
        final CEvaluationItem info = (CEvaluationItem)button.getTag();
        int selectedItem = getSelecledCompare(info.value);

        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selectcompare)
        .setSingleChoiceItems(mBijinpingArray, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        if(which == 0){
                            button.setText("");
                        }else{
                            button.setText(mBijinpingArray[which]);
                        }
                        dialog.dismiss();
                        info.value = mBijinpingValueArray[which];
                    }
                }).show();
    }

    /**
     * 获取考评项索引
     */
    private int getSelecledCompare(String value){
        if(value == null || value.trim().length() == 0 || value.equals(ProductInfoListView.DEFAULT)){
            return 0;
        }else{
            for(int i = 0; i < mBijinpingValueArray.length; i++){
                if(mBijinpingValueArray[i].equals(value)){
                    return i;
                }
            }
        }
        return 0;
    }

    private String getSelectCompareString(String value){
        int sid = getSelecledCompare(value);
        String techen = "";
        if(sid > 0){
            techen = mBijinpingArray[sid];
        }
        return techen;
    }

    public boolean checkInputData(){
        if(mList.size() == 0){
            return true;
        }
        for(int i = 0; i < mList.size(); i++){
            CEvaluationItem item = mList.get(i);
            if(!ProductInfoListView.DEFAULT.equals(item.savedvalue)){
                return true;
            }
        }
        return false;
    }
}
